package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class HandlerException {
    /**
     * 自定义异常处理器
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> SqlException(SQLIntegrityConstraintViolationException e) {
        log.info("拦截到异常{}", e.getMessage());
        //判断异常信息中是否包含Duplicate entry字符
        if (e.getMessage().contains("Duplicate entry")) {
            //包含就处理获取输入得username
            String[] str = e.getMessage().split(" ");
            String username = str[2];
            return R.error(username + "此用户名已存在，请重新输入");
        }
        return R.error("您的网络有问题，请重新输入");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> SqlException(CustomException e) {
        log.info("拦截到异常{}", e.getMessage());
        return R.error(e.getMessage());
    }

}
